package ldh.maker.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.stage.WindowEvent;
import ldh.maker.constants.TreeNodeTypeEnum;
import ldh.maker.db.DbConnectionDb;
import ldh.maker.db.TreeNodeDb;
import ldh.maker.util.ConnectionFactory;
import ldh.maker.util.DialogUtil;
import ldh.maker.util.UiUtil;
import ldh.maker.vo.DBConnectionData;
import ldh.maker.vo.TreeNode;
import org.controlsfx.validation.Severity;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.Validator;

import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;

/**
 * Created by ldh on 2017/2/25.
 */
public class CreateNewConnectionController implements Initializable {

    ValidationSupport validationSupport = new ValidationSupport();

    @FXML
    TextField name;
    @FXML
    TextField ip;
    @FXML
    TextField userName;
    @FXML
    TextField port;
    @FXML
    PasswordField password;

    @FXML
    public void saveBtn() throws SQLException {
        if(validationSupport.isInvalid()) {
            DialogUtil.show(Alert.AlertType.WARNING, "填写错误", "请按照要求填写");
            return;
        }
        DBConnectionData dbConnectionData = buildDbConnectionData();
        TreeNode data = UiUtil.getCurrentTreeNode();
        if (isExist(data, dbConnectionData.getNameProperty())) {
            DialogUtil.show(Alert.AlertType.WARNING, "填写错误", "连接名重复，请换个名称吧");
            return;
        }
        Connection connection = getConnection(dbConnectionData);
        if (connection == null) {
            DialogUtil.show(Alert.AlertType.WARNING, "填写错误", "数据库连接不上");
            return;
        }
        dbConnectionData.setConnection(connection);
        TreeNode treeData = new TreeNode(TreeNodeTypeEnum.DB_CONNECTION, dbConnectionData.getNameProperty(), data);
        treeData.setData(dbConnectionData);

        TreeNodeDb.save(treeData);
        dbConnectionData.setTreeNode(treeData);
        DbConnectionDb.save(dbConnectionData);

        buildUi(treeData);
        data.getChildren().add(treeData);
        name.getScene().getWindow().fireEvent(new WindowEvent(name.getScene().getWindow(), WindowEvent.WINDOW_CLOSE_REQUEST));
    }

    @FXML
    public void closeBtn() {
        name.getScene().getWindow().hide();
    }

    private boolean isExist(TreeNode data, String name) {
        List<TreeNode> dds = data.getChildren();
        for (TreeNode d : dds) {
            if (d.getText().equals(name)) {
                return true;
            }
        }
        return false;
    }

    private Connection getConnection(DBConnectionData dbConnectionData) {
        Connection connection = ConnectionFactory.getConnection(dbConnectionData);
        if (connection != null) {
            return connection;
        }
        return null;
    }

    private void buildUi(TreeNode treeData) {
        TreeItem<TreeNode> data = UiUtil.TREE.getSelectionModel().getSelectedItem();
        TreeItem<TreeNode> dbItem = new TreeItem<>(treeData);
        data.getChildren().addAll(dbItem);
        data.setExpanded(true);
    }

    private DBConnectionData buildDbConnectionData() {
        DBConnectionData dbConnectionData = new DBConnectionData();
        dbConnectionData.setIpProperty(ip.getText().trim());
        dbConnectionData.setNameProperty(name.getText().trim());
        dbConnectionData.setPortProperty(Integer.valueOf(port.getText().trim()));
        dbConnectionData.setUserNameProperty(userName.getText().trim());
        dbConnectionData.setPasswordProperty(password.getText());
        return dbConnectionData;
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        validationSupport.registerValidator(name, Validator.createEmptyValidator("链接不能为空，并且不能重复"));
        validationSupport.registerValidator(ip, Validator.createEmptyValidator("IP不能为空"));
        validationSupport.registerValidator(port, Validator.createRegexValidator("端口不能为空", "^[0-9]*[1-9][0-9]*$", Severity.ERROR));
        validationSupport.registerValidator(userName, Validator.createEmptyValidator("用户名不能为空"));
        validationSupport.registerValidator(password, Validator.createEmptyValidator("密码不能为空"));

        name.setText("localhost");
        ip.setText("localhost");
        port.setText("3306");
        userName.setText("root");
        password.setText("123456");
    }
}
